import '@babel/polyfill';
import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls';
import gsap from 'gsap';
import * as dat from 'dat.gui';

//场景
const scene =new THREE.Scene();

//相机
const camera=new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,200);
camera.position.set(5,3,5);
scene.add(camera);

//渲染器
const renderer=new THREE.WebGL1Renderer({antialias:true});
renderer.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(renderer.domElement);

//mesh
const cubeGoemetry=new THREE.BoxGeometry(5,5,5);
const cubeMaterial=new THREE.MeshBasicMaterial({color:0xffff00});
const cube=new THREE.Mesh(cubeGoemetry,cubeMaterial);
cube.position.set(0,0,0);
scene.add(cube);

//控制
const orbitControls=new OrbitControls(camera,renderer.domElement);
orbitControls.enableDamping=true;

//gui面板
const gui=new dat.GUI();
gui.add(cube.position,'y')
.min(-5)
.max(10)
.step(0.1)
.name('调整y坐标')
.onChange((value)=>{console.log('onChange',value)})
.onFinishChange((value)=>{console.log('onFinishChange',value)});
const obj={
    color:0xff0000,
    changeSize:()=>{
        cube.scale.set(0.5,0.5,0.5);
    },
};
//gui颜色
gui.addColor(obj,'color').onChange((value)=>{
    cube.material.color.set(value);
});
//gui点击事件
gui.add(obj,'changeSize').name('点击缩小mesh');
//gui选项框
gui.add(cube,'visible').name('显示模型');
//gui文件夹
const guiFolder=gui.addFolder('更多设置');
guiFolder.add(cube.material,'wireframe').name('线框渲染');
guiFolder.add(cube.scale,'x').min(0).max(3).step(0.3).name('调整x轴大小');


//dom全屏
window.addEventListener('dblclick',()=>{
    const fullScreenElement=document.fullscreenElement;
    if(!fullScreenElement){
        renderer.domElement.requestFullscreen();
        
    }else{
        document.exitFullscreen();
    }
});

//坐标轴
const axesHelper=new THREE.AxesHelper(5);
scene.add(axesHelper);

//动画(旋转绕局部空间的y轴)
const gsap1=gsap.to(cube.rotation,{y:Math.PI*2,duration:1.5,delay:0.5,repeat:-1,yoyo:true,ease:'none',onStart:()=>{
    gsap.to(cube.position,{x:3,duration:1});
}});
window.addEventListener('dblclick',()=>{
    if(gsap1.isActive()){
        gsap1.pause();
    }else{
        gsap1.resume();
    }
});

//帧动画
function animate(){
    orbitControls.update();
    renderer.render(scene,camera);
    requestAnimationFrame(animate);
};
animate();

//窗口调整侦听
window.addEventListener('resize',()=>{
    camera.aspect=window.innerWidth/window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth,window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
});



